package com.onlinewebgames.login.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

import com.onlinewebgames.login.model.User;

public class UserDB extends SQLiteOpenHelper {
	protected final static String	nombreTabla	= "user";
	protected final static String	nombreBBDD	= "OnlineWebGames";

	protected final static int		ID			= 0;
	protected final static int		USERNAME	= 1;
	protected final static int		PASSWORD	= 2;
	protected final static int		NAME		= 3;
	protected final static String[]	columnsName	= { "id", "username",
			"password"							};

	protected final static String[]	columnsType	= { "INTEGER", "TEXT", "TEXT" };

	public UserDB(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}

	@Override
	public void onCreate (SQLiteDatabase db) {
		StringBuffer crearTabla = new StringBuffer("CREATE TABLE ");
		crearTabla.append(nombreTabla);
		crearTabla.append("(");
		for (int i = 0; i < columnsName.length; i++) {
			crearTabla.append(columnsName[i]);
			crearTabla.append(" ");
			crearTabla.append(columnsType[i]);
			if (i != columnsName.length - 1)
				crearTabla.append(", ");
		}
		crearTabla.append(")");
		db.execSQL(crearTabla.toString());
	}

	@Override
	public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS " + nombreTabla);
		onCreate(db);
	}

	protected static ContentValues transformToRegistro (User user) {
		ContentValues registro = new ContentValues();
		registro.put(UserDB.columnsName[ID], user.getId());
		registro.put(UserDB.columnsName[USERNAME], user.getUsername());
		registro.put(UserDB.columnsName[PASSWORD], user.getPassword());
		return registro;
	}

	protected static User transformToUser (Cursor cursor) {
		User user = null;
		if (cursor.moveToFirst()) {
			user = new User();
			user.setId(cursor.getInt(UserDB.ID));
			user.setUsername(cursor.getString(UserDB.USERNAME));
			user.setPassword(cursor.getString(UserDB.PASSWORD));
		}
		return user;
	}
}
